import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import '../data/data_history.dart';

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '秒表',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<DataHistory> histories = [];
  String title = "00:00:00 000";

  bool running = false;

  DateTime? lastDateTime;
  DateTime? startDateTime;
  Timer? timer;

  void captureTime() {
    String dTimeStr = "00:00 000";

    DateTime dateTime = DateTime.now();
    if (running) {
      //打点
      int dTime = (dateTime.millisecondsSinceEpoch - lastDateTime!.millisecondsSinceEpoch);
      dTimeStr = transTime(dTime);
      lastDateTime = dateTime;
    } else {
      start(dateTime);
    }

    //当前数据
    var dataHistory = DataHistory(DateFormat("HH:mm:ss SSS").format(lastDateTime!), dTimeStr,
        transTime(lastDateTime!.millisecondsSinceEpoch - startDateTime!.millisecondsSinceEpoch));

    setState(() {
      histories.add(dataHistory);
    });
  }

  // 开始秒表
  void startOrStopWatch() {
    if (running) {
      timer = Timer.periodic(const Duration(milliseconds: 30), (timer) {
        int dTime = DateTime.now().millisecondsSinceEpoch - startDateTime!.millisecondsSinceEpoch;
        String stopWatch =
            DateFormat("HH:mm:ss SSS").format(DateTime.fromMillisecondsSinceEpoch(dTime - 8 * 60 * 60 * 1000));
        setState(() {
          title = stopWatch;
        });
      });
    } else {
      timer?.cancel();
    }
  }

  //时间格式化
  String transTime(int dTime) {
    int min = dTime ~/ 60000;
    int dTime2 = dTime % 60000;
    int sec = dTime2 ~/ 1000;
    int mil = dTime2 % 1000;

    return addZero(min, 2) + ":" + addZero(sec, 2) + " " + addZero(mil, 3).toString();
  }

  // 加0
  String addZero(int value, int length) {
    String result = "";
    for (var i = 1; i <= length - 1; i++) {
      if (value < pow(10, i)) {
        result += "0";
      }
    }
    return result + value.toString();
  }

  //开始
  void start(DateTime dateTime) {
    running = true;
    lastDateTime = startDateTime = dateTime;
    startDateTime = startDateTime;
    startOrStopWatch();
  }

  // 停止
  void stop() {
    running = false;
    startOrStopWatch();
  }

  // 清除数据
  void resetTime() {
    setState(() {
      running = false;
      histories.clear();
      lastDateTime = null;
      startDateTime = null;
    });
    start(DateTime.now());
  }

  // 合并数据
  List<RichText> mergeHistories(List<DataHistory> histories) {
    List<RichText> data = [];
    histories.asMap().forEach((key, value) {
      data.add(value.transToRichText(key));
    });
    return data;
  }

  @override
  Widget build(BuildContext context) {
    List<RichText> richTexts = mergeHistories(histories);
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: [
              MaterialButton(
                color: Colors.red,
                onPressed: stop,
                child: const Text("停止"),
              ),
              MaterialButton(
                color: Colors.red,
                onPressed: resetTime,
                child: const Text("重置"),
              ),
            ],
          ),
          Flexible(
              child: SingleChildScrollView(
                  child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: richTexts,
          ))),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: captureTime,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
